import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/network/xindong_response.dart';

abstract class XinDongCommonVM extends GetxController {
  bool hasMore = false; // 是否有下一页
  int yemian = 0; // 页码，从0开始
  List? dataList; // 数据集合
  final bool initialRefresh; // 初始化时是否自动刷新
  final ScrollController scrollController = ScrollController(initialScrollOffset: 0); // 滚动控制器
  late RefreshController refreshController; // 刷新加载控制器
  late bool isLoading = false; // 正在加载中
  late bool isLoadingMore = false; // 正在加载更多中

  // 基类构造函数
  XinDongCommonVM({this.initialRefresh = true}) {
    refreshController = RefreshController(initialRefresh: initialRefresh);
  }

  // 通知刷新
  void notifyRefresh() {
    if (isLoading == true) {
      return;
    }
    refreshController.requestRefresh(needMove: true, duration: const Duration(milliseconds: 200));
  }

  // 刷新数据
  //
  // 重置控件、刷新完成、刷新失败
  void refreshData({NetworkResponse? object}) {
    refreshController.resetNoData();
    if (object != null && object.code == XinDongServerStatus.success) {
      refreshController.refreshCompleted();
    } else {
      dataList ??= []; // 加载失败，如果为null，就赋值吧
      refreshController.refreshFailed();
    }
    update();
  }

  // 提前加载
  void isLoadMoreData() {
    if (isLoadingMore == true || dataList == null) {
      return;
    }
    isLoadingMore = true;
    loadMoreData();
  }

  // 加载更多数据
  //
  // 加载完成、加载至最后没有更多数据、加载失败
  void loadMoreData({NetworkResponse? object}) {
    if (object != null && object.code == XinDongServerStatus.success) {
      if (hasMore == false) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
    } else {
      refreshController.loadFailed();
    }
    Future.delayed(const Duration(milliseconds: 1000)).whenComplete(() => isLoadingMore = false);
    update();
  }

  // 删除本地数据
  void deleteWithClass(model) {
    dataList?.remove(model);
    update();
  }

  // 为避免出现 Null check operator used on a null value
  bool _disposed = false;

  // 重写销毁方法
  @override
  void dispose() {
    _disposed = true;
    refreshController.dispose();
    scrollController.dispose();
    super.dispose();
  }

  // 通知监听器进行数据刷新
  @override
  void update([List<Object>? ids, bool condition = true]) {
    if (!_disposed) {
      super.update(ids, condition);
    } else {
      mDebugPrint('销毁了，不要再调用了');
    }
  }
}
